package fr.vvins.core.biz.auth;

import org.springframework.beans.factory.annotation.Autowired;

import fr.vvins.core.biz.auth.dto.LocalCredentialDtoImpl;
import fr.vvins.core.biz.user.UserException;
import fr.vvins.core.biz.user.UserManager;
import fr.vvins.core.biz.user.dto.CredentialDto;
import fr.vvins.core.biz.user.dto.UserDto;
import fr.vvins.core.common.TechnicalException;

public class LocalAuthManagerImpl implements AuthManager {
	@Autowired
	public UserManager userManager;
	
	@Override
	public UserDto authenticate(CredentialDto credential) throws TechnicalException, UserException {
		String login = ((LocalCredentialDtoImpl)credential).getLogin();
		String password = ((LocalCredentialDtoImpl)credential).getPassword();
		UserDto user = userManager.findUserByLogin(login);
		if(user == null){
			throw new UserException(UserException.NOT_FOUND, "User not found");
		}
		if(!checkPassword(password, user)){
			throw new UserException(UserException.BAD_PASS, "Error during authentication");
		}
		return user;
	}
	
	private boolean checkPassword(String password, UserDto user){
		//TODO : password encoding
		if(password.equals(user.getPassword())){
			return true;
		}
		return false;
	}

}
